package com.zhanghp.class036;

import com.zhanghp.common.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * 利用先序与中序遍历序列构造二叉树<br/>
 * 测试链接 : https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 *
 * @author zhanghp
 * @since 2024/4/19 9:44
 */
public class Code07_PreorderInorderBuildBinaryTree {

    public static void main(String[] args) {
        int[] p = {3,9,20,15,7};
        int[] o = {9,3,15,20,7};
        TreeNode node = new Solution().buildTree(p, o);
    }

    static class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if (preorder == null || inorder == null || preorder.length != inorder.length) {
                return null;
            }
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < inorder.length; i++) {
                map.put(inorder[i], i);
            }
            return f(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
        }

        public TreeNode f(int[] preorder, int pl, int pr, int[] inorder, int il, int ir, Map<Integer, Integer> map) {
            if (pl > pr) {
                return null;
            }
            TreeNode head = new TreeNode(preorder[pl]);
            if (pl == pr) {
                return head;
            }
            Integer kIndex = map.get(head.val);
            // 利用中序的左右节点，来确定先序的左右索引位置
            head.left = f(preorder, pl + 1, pl + kIndex - il, inorder, il, kIndex - 1, map);
            // 中序，左右索引，需要传，用来先序的边界确定
            head.right = f(preorder, pl + kIndex - il + 1, pr, inorder, kIndex + 1, ir, map);
            return head;

        }

    }

    // // 中序，左右索引，需要传，用来先序的边界确定
    static class WrongSolution{
        public TreeNode buildTree2(int[] preorder, int[] inorder) {
            if (preorder == null || inorder == null || preorder.length != inorder.length) {
                return null;
            }
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < inorder.length; i++) {
                map.put(inorder[i], i);
            }
            return f2(preorder, 0, preorder.length - 1,  map);
        }
        public TreeNode f2(int[] preorder, int pl, int pr, Map<Integer, Integer> map) {
            if (pl > pr) {
                return null;
            }
            TreeNode head = new TreeNode(preorder[pl]);
            if (pl == pr) {
                return head;
            }
            Integer kIndex = map.get(head.val);
            // 利用中序的左右节点，来确定先序的左右索引位置
            head.left = f2(preorder, pl + 1, pl + kIndex , map);
            head.right = f2(preorder, pl + kIndex + 1, pr,  map);
            return head;

        }
    }
}
